package doyyin;

import cn.hutool.core.util.StrUtil;

import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class UrlUtils {

    /**
     * 解析 URL 中的查询参数，支持中文、多值
     */
    public static Map<String, List<String>> getQueryParams(String url) throws Exception {
        URI uri = new URI(url);
        String query = uri.getRawQuery(); // 保留原始编码（避免中文乱码）
        Map<String, List<String>> paramMap = new LinkedHashMap<>();

        if (query != null && !query.isEmpty()) {
            String[] pairs = query.split("&");
            for (String pair : pairs) {
                int idx = pair.indexOf('=');
                String key = idx > 0 ? pair.substring(0, idx) : pair;
                String value = idx > 0 && pair.length() > idx + 1 ? pair.substring(idx + 1) : "";

                key = URLDecoder.decode(key, StandardCharsets.UTF_8.name());
                value = URLDecoder.decode(value, StandardCharsets.UTF_8.name());

                paramMap.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
            }
        }

        return paramMap;
    }

    /**
     * 简化版：仅返回每个 key 的第一个值
     */
    public static Map<String, String> getFirstQueryParams(String url) throws Exception {
        Map<String, List<String>> multiMap = getQueryParams(url);
        Map<String, String> singleMap = new LinkedHashMap<>();
        for (Map.Entry<String, List<String>> entry : multiMap.entrySet()) {
            if (!entry.getValue().isEmpty()) {
                singleMap.put(entry.getKey(), entry.getValue().get(0));
            }
        }
        return singleMap;
    }

    /**
     * 获取url
     * @param url
     * @return
     */
    public static String getUrl(String url){
        return StrUtil.subBefore(url, "?", true);
    }

    /**
     * 将url和参数进行拼接
     * @param args
     * @throws Exception
     */
    public static String getUrlWithParams(String url, Map<String, String> args) {
        StringBuilder sb = new StringBuilder(getUrl(url));
        sb.append("?");
        for (Map.Entry<String, String> entry : args.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        return sb.substring(0, sb.length() - 1);
    }

    // 示例用法
    public static void main(String[] args) throws Exception {
         String url="https://www-hj.douyin.com/aweme/v1/web/user/following/list/?device_platform=webapp&aid=6383&channel=channel_pc_web&user_id=101698474497&sec_user_id=MS4wLjABAAAAVpIeSY_InKKDik9DB4op5Ttj5UEK46lWlna5VoE4gS8&offset=0&min_time=0&max_time=0&count=10&source_type=4&gps_access=0&address_book_access=0&is_top=1&update_version_code=170400&pc_client_type=1&pc_libra_divert=Windows&support_h265=1&support_dash=1&cpu_core_num=8&version_code=170400&version_name=17.4.0&cookie_enabled=true&screen_width=1536&screen_height=864&browser_language=zh-CN&browser_platform=Win32&browser_name=Chrome&browser_version=136.0.0.0&browser_online=true&engine_name=Blink&engine_version=136.0.0.0&os_name=Windows&os_version=10&device_memory=8&platform=PC&downlink=10&effective_type=4g&round_trip_time=100&webid=7494581555790186025&uifid=4be83ecefa579a300714166db9e569bafd8689fc248d1e190e384db8df203b81a32c9a0b72bebfad256c647900b4ef78e5aafc0fcf86d3a7e9d0256a7a9819b4e300b0bffd544added228ac07a31f37c4da215b614a5b51aba9f2349ee4c765982fe994039f84d60c0a4829e49be406d8bf228c2e14233b531e3f6e739146bce450c8335590b6bae8ca8e9fe1eea37db065265be1e86322d5b449556d94113a7&verifyFp=verify_m9ml1uqd_Z8cjHptX_wUEn_4FCk_90v5_HnQnjVqrfJNd&fp=verify_m9ml1uqd_Z8cjHptX_wUEn_4FCk_90v5_HnQnjVqrfJNd&msToken=jznGzPo-n8WVtpGpLCycaeDWQHEDoElJ1TqBN1hAWRDd6TUKltbLqi3omiLUEluBhd4C3GFZ1Hql4EL3tTHx1RFnXC6jthSf-XrqURd_XCk8pAwhnLwIJwxZ6SOu2wP2x3QWcfg_nbcXLefEcWmm9UOlkiYej9CLSnVEgSSSrEGs&a_bogus=d64fDwtLQ2AncdKtYOPCyUcl7KEMNTWyfZiOWLZT7PYaGqtc5uP4dabobxqhJIrauSMkk13H-J4lunxc%2FTUwZe9kKmpvu2syQz5VngfL21N6Y0JQLqgkez4zoXMK8YGza%2FV9i1JIhUGw1jd-iqdE%2FBVSeKOK5Y8h%2F3ORk2TSx9ah1z6AgZnaPQSdThGqYD%3D%3D"
                 ;

        Map<String, String> fullParams = getFirstQueryParams(url);
        System.out.println("多值参数:");
        fullParams.forEach((k, v) -> System.out.println(StrUtil.format("param.add(\"{}\")", k)));


    }
}
